﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Parichay.Domain; using Parichay.Domain.Models;
using Parichay.Data.Helper;

namespace Parichay.MVC.Controllers
{
    public class MediaController : AuthController
    {
        public ActionResult Index()
        {
            IList<MemberUploads> myFiles = NHibernateHelper.FetchProjection<MemberUploads>(new string[] { "Id", "Attachmt", "FileSize", "CreateD" }, "Owner.Id", LoggedInUserKey,null,null,false,null,false);
            return View(myFiles);
        }

        [Authorize]
        [HttpPost]
        public ActionResult Add()
        {
            try
            {
                SaveImage();
            }
            catch (Exception exc1)
            {
                TempData["message"] = exc1.Message;
            }
            return RedirectToAction("Index");
        }

        [Authorize]
        [HttpPost]
        public ActionResult AddFile()
        {
            try
            {
                SaveDoc();
            }
            catch (Exception exc1)
            {
                TempData["message"] = exc1.Message;
            }
            return RedirectToAction("Index");
        }

        [Authorize]
        [HttpPost]
        public ActionResult AddAvatar()
        {
            try
            {
                SaveAvImage();
            }
            catch (Exception exc1)
            {
                TempData["message"] = exc1.Message;
            }
            return RedirectToAction("Edit", "Account");
        }

        public ActionResult Avatar(Int32? id)
        {
            if(!id.HasValue)
            {
                return(new ImageResult(Utilities.FileToArray(Utilities.GetPhysicalLocation("Content/images/empty.jpg")), "image/jpeg","avatar.jpg"));
            }
            else
            {
            int avId = id.Value;
            //This is  method for getting the image information
            // including the image byte array from the image column in
            // a database.
            MemberUploads image = NHibernateHelper.UniqueResult<MemberUploads>(null, "Id", avId);

            //As you can see the use is stupid simple.  Just get the image bytes and the
            //  saved content type.  See this is where the contentType comes in real handy.
            ImageResult result=null;
                
                if(image != null)
                {
                    if (image.UploadedMediaLocation==UploadedMediaLocation.Database)
                    {
                        result = new ImageResult(image.FileDetail, image.FileContentT, "avatar.jpg");
                    }
                    else
                    {
                        FileUploadModel fr = new FileUploadModel(image.SectionNo);
                        result = new ImageResult(fr.getAbosoluteFilePath(), fr.ContentType, fr.FileName);
                    }
                
                }
                else { new ImageResult(Utilities.FileToArray(Utilities.GetPhysicalLocation("Content/images/empty.jpg")), "image/jpeg", "avatar.jpg"); }
            return result;
            }
        }




        public ActionResult AvatarByUId(Int32 id)
        {

            int? picId = NHibernateHelper.UniqueResult<MemberDetails>("PicId", "Id", id).PicId;
            //This is method for getting the image information
            // including the image byte array from the image column in
            // a database.
            MemberUploads image = NHibernateHelper.UniqueResult<MemberUploads>(null, "Id", picId.HasValue ? picId : 0);
            //As you can see the use is stupid simple.  Just get the image bytes and the
            //  saved content type.  See this is where the contentType comes in real handy.
            ImageResult result = new ImageResult(image.FileDetail, image.FileContentT,"avatar.jpg");

            return result;
        }

        [Authorize]
        [HttpPost]
        public ActionResult DeleteAvatar()
        {
            MemberDetails usr = NHibernateHelper.UniqueResult<MemberDetails>(null, "Id", LoggedInUserKey);

            ////Delete previous avatar image if any
            if ((usr.PicId.HasValue) && (usr.PicId.Value != 0))
            {
                MemberUploads itm = NHibernateHelper.UniqueResult<MemberUploads>(null, "Id", usr.PicId.Value);

                if (itm != null)
                    NHibernateHelper.Delete<MemberUploads>(itm);

                TempData["message"] = "Your Avatar Image is deleted Now.";
            }

            return RedirectToAction("Edit", "Account");
        }

        private bool isImage(string fileName, bool ignoreCase)
        {
            string[] acceptedImgExt = new string[] { ".jpg", ".jpeg", ".bmp", ".gif", ".jpeg", ".png", ".tif" };
            string FileExtention = System.IO.Path.GetExtension(fileName);

            for (int i = 0; i <= acceptedImgExt.Length - 1; i++)
            {
                if ((string.Compare(FileExtention, acceptedImgExt[i], ignoreCase) == 0))
                    return true;
            }

            return false;
        }

        private void SaveAvImage()
        {
            ////Delete previous avatar image if any
            //MemberUploads itm = NHibernateHelper.UniqueResult<MemberUploads>(null, "Id", LoggedInUserKey);
            //if (itm != null)
            //    NHibernateHelper.Delete<MemberUploads>(itm);

            foreach (string inputTagName in Request.Files)
            {
                HttpPostedFileBase file = HttpContext.Request.Files[inputTagName];



                if (isImage(file.FileName, true))
                {

                    MemberDetails usr = NHibernateHelper.UniqueResult<MemberDetails>(null, "Id", LoggedInUserKey);

                    ////Delete previous avatar image if any
                    ////Delete previous avatar image if any
                    if ((usr.PicId.HasValue) && (usr.PicId.Value != 0))
                    {
                        MemberUploads itm = NHibernateHelper.UniqueResult<MemberUploads>(null, "Id", usr.PicId.Value);

                        if (itm != null)
                            NHibernateHelper.Delete<MemberUploads>(itm);
                    }


                    if (file.ContentLength > 0)
                    {

                        TempData["message"] = "Resizing the file '" + file.FileName + "' to avatar Image now.";

                        MemberUploads attch = new MemberUploads();
                        attch.Owner = usr;//NHibernateHelper.UniqueResult<MemberDetails>(null,"Id",LoggedInUserKey);
                        attch.Attachmt = file.FileName;

                        attch.FileContentT = file.ContentType;
                        //attch.FileSize = file.ContentLength;
                        attch.CreateD = DateTime.Now;
                        attch.FileDetail = Utilities.CreateAvatar(100, file.InputStream);
                        attch.FileSize = attch.FileDetail.Length;
                        NHibernateHelper.Save<MemberUploads>(attch);
                        //Save the attachment into database according to the paperId, conferenceCode etc
                        usr.PicId = attch.Id;
                        NHibernateHelper.Update<MemberDetails>(usr);

                    }
                }
                else
                {
                    throw new Exception("Only JPG , BMP , PNG , GIF and TIF files can be uploaded as profile image.");
                }
            }
        }

        private Byte[] Convert(HttpPostedFileBase source)
        {
            Byte[] destination = new Byte[source.ContentLength];
            source.InputStream.Position = 0;
            source.InputStream.Read(destination, 0, source.ContentLength);
            return destination;
        } // Convert

        private void SaveImage()
        {
            ////Delete previous avatar image if any
            //MemberUploads itm = NHibernateHelper.UniqueResult<MemberUploads>(null, "Id", LoggedInUserKey);
            //if (itm != null)
            //    NHibernateHelper.Delete<MemberUploads>(itm);

            foreach (string inputTagName in Request.Files)
            {
                HttpPostedFileBase file = HttpContext.Request.Files[inputTagName];



                if (isImage(file.FileName, true))
                {

                    MemberDetails usr = NHibernateHelper.UniqueResult<MemberDetails>(null, "Id", LoggedInUserKey);

                    int MyfileCount = NHibernateHelper.Count("select a.Id from MemberUploads a where a.Owner.Id=?", LoggedInUserKey,NHibernate.NHibernateUtil.Int32,false);

                    if (MyfileCount > 10)
                    {
                        throw new Exception("Maximum 10 file uploads are allowed per user. To upload more, please remove any of previous uploads.");
                    }

                    if (file.ContentLength > 0)
                    {

                        //TempData["message"] = "Resizing the file '" + file.FileName + "' to avatar Image now.";

                        MemberUploads attch = new MemberUploads();
                        attch.Owner = usr;
                        attch.Attachmt = file.FileName;

                        attch.FileContentT = file.ContentType;
                        //attch.FileSize = file.ContentLength;
                        attch.CreateD = DateTime.Now;
                        attch.FileDetail = Convert(file); //Utilities.CreateAvatar(100, file.InputStream);
                        attch.FileSize = attch.FileDetail.Length;
                        NHibernateHelper.Save<MemberUploads>(attch);
                        //Save the attachment into database according to the paperId, conferenceCode etc
                        //usr.PicId = attch.Id;
                        //NHibernateHelper.Update<MemberDetails>(usr);

                        //string filePath = Path.Combine(@"C:\MyUploadedFiles", Path.GetFileName(file.FileName));
                        //file.SaveAs(filePath);
                    }
                }
                else
                {
                    throw new Exception("Only JPG , BMP , PNG , GIF and TIF files can be uploaded as profile image.");
                }
            }
        }

        private void SaveDoc()
        {
            ////Delete previous avatar image if any
            //MemberUploads itm = NHibernateHelper.UniqueResult<MemberUploads>(null, "Id", LoggedInUserKey);
            //if (itm != null)
            //    NHibernateHelper.Delete<MemberUploads>(itm);

            foreach (string inputTagName in Request.Files)
            {
                HttpPostedFileBase file = HttpContext.Request.Files[inputTagName];



                if (isImage(file.FileName, true))
                {
                    if (file.ContentLength>0)
                    {
                        uploadDoc(file, false, UploadedMediaOperationType.None, 0, 0);
                    }
                }
                else
                {
                    throw new Exception("Only JPG , BMP , PNG , GIF and TIF files can be uploaded as profile image.");
                }
            }
        }

        private FileUploadModel uploadDoc(HttpPostedFileBase file, bool saveToDB, UploadedMediaOperationType operationType, int width, int height)
        {

            //string allowTypes = CustomConfigManager.getSetting("AllowToUploadFileOfType", ".xls,.xlsx,.ppt,.pptx,.pdf,.doc,.docx,.txt,.htm");
            string allowTypes = ".jpg,.jpeg,.gif,.png";
            string[] seperator = new string[] { "," };
            string[] types = allowTypes.Split(seperator, StringSplitOptions.RemoveEmptyEntries);

            string maxFileSize = Utilities.getConfigSetting("MaxFileSizeInKb", "1024");
            int iMaxFileSize = int.Parse(maxFileSize) * 1024;

            if (file != null)
            {
                if (!types.Contains(System.IO.Path.GetExtension(file.FileName).ToLower()))
                {
                    return (new FileUploadModel { IsSuccess = false, StatusMessage = "error: Attachment type is not allowed. Please only upload files of these types: " + allowTypes });
                }

                if (file.ContentLength > iMaxFileSize)
                {
                    return (new FileUploadModel { IsSuccess = false, StatusMessage = "error: Attachment is too big. Please upload file smaller than " + maxFileSize + " Kb" });
                }



                FileUploadModel resp = new FileUploadModel(file);
                byte[] buffer = null;

                switch (operationType)
                {
                    case UploadedMediaOperationType.Resize:
                        buffer = Utilities.ResizeImage(width, height, file.InputStream);
                        resp.ContentLength = buffer.Length;
                        break;
                    case UploadedMediaOperationType.Crop:
                        buffer = Utilities.CropImage(0, 0, width, height, file.InputStream);
                        resp.ContentLength = buffer.Length;
                        break;
                    case UploadedMediaOperationType.None:
                    default:
                        buffer = Utilities.readInputStreamToBytes(file.InputStream);
                        resp.ContentLength = buffer.Length;
                        break;
                }


                if (saveToDB)
                {
                    MemberDetails usr = NHibernateHelper.UniqueResult<MemberDetails>(null, "Id", LoggedInUserKey);
                    //Save to Database here
                    MemberUploads attch = new MemberUploads();
                    attch.Owner = usr;
                    attch.Attachmt = file.FileName;

                    attch.FileContentT = file.ContentType;
                    //attch.FileSize = file.ContentLength;
                    attch.CreateD = DateTime.Now;
                    attch.FileDetail = Convert(file); //Utilities.CreateAvatar(100, file.InputStream);
                    attch.FileSize = attch.FileDetail.Length;
                    attch.UploadedMediaLocation = UploadedMediaLocation.Database;
                    NHibernateHelper.Save<MemberUploads>(attch);
                }
                else
                {
                    //Target File is to be saved to Directory exists or not
                    if (System.IO.File.Exists(resp.getAbosoluteFilePath()))
                    {
                        return (new FileUploadModel { IsSuccess = false, StatusMessage = "error: Some error has occured while uploading the file, please try again!" });
                    }

                    if (!System.IO.Directory.Exists(resp.getAbsoluteLocation()))
                    {
                        System.IO.Directory.CreateDirectory(resp.getAbsoluteLocation());
                    }

                    resp.writeBytesToFileLocation(buffer);

                    MemberDetails usr = NHibernateHelper.UniqueResult<MemberDetails>(null, "Id", LoggedInUserKey);
                    //Save to Database here
                    MemberUploads attch = new MemberUploads();
                    attch.Owner = usr;
                    attch.Attachmt = file.FileName;

                    attch.FileContentT = file.ContentType;
                    //attch.FileSize = file.ContentLength;
                    attch.CreateD = DateTime.Now;
                    attch.FileDetail = null; //Utilities.CreateAvatar(100, file.InputStream);
                    attch.FileSize = buffer.Length;
                    attch.UploadedMediaLocation = UploadedMediaLocation.FileFolder;
                    attch.SectionNo = resp.ToString();
                    NHibernateHelper.Save<MemberUploads>(attch);
                }

                resp.StatusMessage = "success: " + resp.getAbsoluteLocation() + resp.ToString();
                resp.IsSuccess = true;
                return (resp);
            }
            else
            {
                return (new FileUploadModel { StatusMessage = "error: No file was uploaded.", IsSuccess = false });
            }

        }


        [Authorize]
        public ActionResult Delete(int id)
        {
            try
            {
                NHibernateHelper.Delete("from MemberUploads a where a.Id=? and a.Owner.Id=?", new object[] { id, LoggedInUserKey }, new NHibernate.Type.IType[] { NHibernate.NHibernateUtil.Int32, NHibernate.NHibernateUtil.Int32 });
            }
            catch (Exception ex1)
            {
                TempData["message"] = "Unable to delete." + ex1.Message;
            }
            return RedirectToAction("Index");
        }
    }
}
